//
//  ChoicenessViewController.m
//  IntimateGift
//
//  Created by zh on 14/12/17.
//  Copyright (c) 2014年 蔡宏业. All rights reserved.
//

#import "ChoicenessViewController.h"
#import "UIColor+AddColor.h"
#import "NetHandler.h"
#import "UIImageView+WebCache.h"
#import "ChoicenessCell.h"
#import "Choiceness.h"
#import "UIScrollView+Extension.h"
#import "UIScrollView+MJRefresh.h"
#import "DetailsViewController.h"
#import "TapScrollViewViewController.h"
#import "MMDrawerBarButtonItem.h"
#import "UIViewController+MMDrawerController.h"
#import "MBProgressHUD.h"
#import "Reachability.h"
//#import "ZBarSDK.h"


#define CHOICENESS @"choicenessReuse"

@interface ChoicenessViewController () <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
// 最底层的scrollView
@property (nonatomic, retain) UIScrollView *bigScrollView;
// 最上面的scrollView
@property (nonatomic, retain) UIScrollView *topScrollView;
@property (nonatomic, retain) UIPageControl *topPageControl;
@property (nonatomic, retain) UIImageView *myImgView;
@property (nonatomic, retain) UIView *topView;
// 存topScrollView的对象
@property (nonatomic, retain) NSMutableArray *bannersArr;

@property (nonatomic, retain) UITableView *myTableView;
// 存tableView的对象
@property (nonatomic, retain) NSMutableArray *arr;

@property (nonatomic, assign) NSInteger num;

@property (nonatomic, assign) NSInteger sum;

@property (nonatomic, retain) UILabel *myLabel;

@property (nonatomic, retain) UIAlertView *myAlertView;

@property (nonatomic, retain) MBProgressHUD *hud;

@end

@implementation ChoicenessViewController



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.alpha = 1;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
    
    [super viewWillAppear:animated];
    // 视图将要出现时, 将navigationBar 的hidden设置为NO
//    self.navigationController.navigationBarHidden = NO;
    
    // 判断网络字符串是否为空
    if ([self GetCurrntNet]) {
        // 不为空, 则处理网络数据
        // 调用数据处理方法
        NSString *str = @"http://api.liwushuo.com/v1/channels/1/items?limit=12&offset=0";
        [NetHandler getDataWithUrl:str completion:^(NSData *data) {
            
            NSError *error = nil;
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            NSDictionary *dic1 = [result objectForKey:@"data"];
            NSArray *arr = [dic1 objectForKey:@"items"];
            [self.arr removeAllObjects];
            for (NSDictionary *dic in arr) {
                Choiceness *choiceness = [[Choiceness alloc] initWithDictionary:dic];
                [self.arr addObject:choiceness];
            }
            [self.myTableView reloadData];
            [self.hud removeFromSuperview];
        }];
        
    }else {
        // 否则检查网络
        self.hud.labelText = @"请检查您的网络";
    }
    // 刷新数据
    [self.myTableView reloadData];
    
}
#pragma mark 初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // 初始化两个数组
        self.arr = [NSMutableArray array];
        self.bannersArr = [NSMutableArray array];
        self.num = 12;
        self.sum = 0;
    }
    return self;
}
#pragma mark scrollView网络请求
// 处理数据
- (void)handleData
{
    // 网络请求
    NSString *str = @"http://api.liwushuo.com/v1/banners";
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        // 解析数据
        NSError *error = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *dic = [NSDictionary dictionary];
        // 找出数组
        dic = [result objectForKey:@"data"];
        NSArray *arr = [dic objectForKey:@"banners"];
        for (NSDictionary *dic1 in arr) {
            // kvc赋值
            BannerGift *bannerGift = [[BannerGift alloc] initWithDictionary:dic1];
            // 把对象添加到数组
            [self.bannersArr addObject:bannerGift];
            
            //            [bannerGift release];
        }
        [self installTopScrollView];
        [self installMyTableView];
        [self setupRefresh];
    }];
    
}
//// 设置bigScrollView的各种属性
//- (void)installBigScrollView
//{
//
//    self.bigScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
//    [self.view addSubview:self.bigScrollView];
//    self.bigScrollView.contentSize = CGSizeMake(0, (self.arr.count) * 200 + 200 + 64);
//    self.bigScrollView.scrollsToTop = YES;
//    self.bigScrollView.showsHorizontalScrollIndicator = NO;
//    self.bigScrollView.showsVerticalScrollIndicator = NO;
//    [_bigScrollView release];
//
//}

#pragma mark 设置topScrollView
// 设置topScrollView的各种属性
- (void)installTopScrollView
{
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height * 0.26)];
    [self.myTableView.tableHeaderView addSubview:self.topView];
    self.topView.backgroundColor = [UIColor clearColor];
    
    self.topScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height * 0.26)];
    self.topScrollView.backgroundColor = [UIColor clearColor];
    [self.topView addSubview:self.topScrollView];
    //8张图片设置topScroll滚动范围为数组+2张图片的大小
    self.topScrollView.contentSize = CGSizeMake(self.view.bounds.size.width * (self.bannersArr.count + 2), 0);
    //按页滑动
    self.topScrollView.pagingEnabled = YES;
    self.topScrollView.delegate = self;
    self.topScrollView.showsHorizontalScrollIndicator = NO;
    //设置初始偏移量
    [self.topScrollView setContentOffset:CGPointMake(self.view.bounds.size.width, 0)];
    //scrollView.directionalLockEnabled = YES;
    self.bannerGift = [[BannerGift alloc] init];
    for (int i = 0; i < self.bannersArr.count + 2; i++) {
        //遍历把图片加到topScroll上边
        if (i == 0) {
            self.bannerGift = [self.bannersArr objectAtIndex:self.bannersArr.count - 1];
        } else if (i == self.bannersArr.count + 1) {
            self.bannerGift = [self.bannersArr objectAtIndex:0];
        } else{
            self.bannerGift = [self.bannersArr objectAtIndex:i - 1];
        }
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width * i, 0, self.view.bounds.size.width, self.view.bounds.size.height * 0.26)];
        imageView.backgroundColor = [UIColor blueColor];
        // 让图片响应交互
        imageView.userInteractionEnabled = YES;
        // 轻拍
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [imageView addGestureRecognizer:tap];
        // 需要的点击次数
        tap.numberOfTapsRequired = 1;
        // 需要几个手指点击
        tap.numberOfTouchesRequired = 1;
        [self.topScrollView addSubview:imageView];
        NSString *str = self.bannerGift.image_url;
        str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:str];
        [imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zhanwei.jpg"]];
//        [imageView setImageWithURL:url];
        [imageView release];
        
        //[_bannerGift release];
        
        
    }
    self.topPageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height * 0.24 - 10, self.view.bounds.size.width, 10)];
    self.topPageControl.backgroundColor = [UIColor clearColor];
    
    [self.topView addSubview:self.topPageControl];
    //    [self.view bringSubviewToFront:self.topPageControl];
    //滚动条
    self.topPageControl.numberOfPages = self.bannersArr.count;
    //设置滚动条不能滑动。
    self.topPageControl.userInteractionEnabled = NO;
    //滚动条颜色
    self.topPageControl.currentPageIndicatorTintColor = [UIColor redColor];
    [self.topPageControl addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
    [_topPageControl release];
    [_topView release];
    [_topScrollView release];
}



- (void)pageAction:(UIPageControl *)topPageControl
{
    //翻页修改topScrollView偏移量
    [self.topScrollView setContentOffset:CGPointMake(topPageControl.currentPage * self.topScrollView.bounds.size.width, 0)] ;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    //NSLog(@"%f", scrollView.contentOffset.x);
    //当偏移量大于n个屏幕宽度是将偏移量变为第一张图片的偏移量
//    NSLog(@"%ld",self.bannersArr.count);
    if (self.topScrollView.contentOffset.x > self.view.bounds.size.width * self.bannersArr.count) {
        [self.topScrollView setContentOffset:CGPointMake(self.view.bounds.size.width, 0)];

    }
    //当偏移量小于第一张图片的偏移量偏移量变为最后一张图片的偏移量
    if (self.topScrollView.contentOffset.x < self.view.bounds.size.width) {
        [self.topScrollView setContentOffset:CGPointMake(self.view.bounds.size.width  * self.bannersArr.count, 0)];
    }
    //由于初始偏移量为屏幕宽度所以得到的页数 - 1
    self.topPageControl.currentPage = (self.topScrollView.contentOffset.x / self.topScrollView.bounds.size.width) - 1;
}


#pragma mark 点击topScrollView(轻拍)
// 轻拍的方法
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    // 属性传值
    BannerGift *banner = [[BannerGift alloc] init];
    banner = [self.bannersArr objectAtIndex:self.topPageControl.currentPage];
    // 判断点击的是百元以内送好礼界面
    if ([banner.type isEqualToString:@"post"] && ![[banner.ScrollViewid description] isEqualToString:@"65"]) {
        
        DetailsViewController *detailsVC = [[DetailsViewController alloc] init];
        detailsVC.banner = banner;
        detailsVC.mark = 1;
        [self.navigationController pushViewController:detailsVC animated:YES];
//        [detailsVC release];
    // 判断点击的时签到界面
    } else if ([[banner.ScrollViewid description] isEqualToString:@"55"]) {
        
     
    // 判断点击其他界面（都相同）
    }else if ([[banner.ScrollViewid description] isEqualToString:@"65"]){
        
    }
    else {
        
        TapScrollViewViewController *tapVC = [[TapScrollViewViewController alloc] init];
        tapVC.banner = banner;
        [self.navigationController pushViewController:tapVC animated:YES];
        [tapVC release];
        
    }
//    NSLog(@"%ld", self.topPageControl.currentPage);
//    NSLog(@"%ld", self.bannersArr.count);
//    NSLog(@"%@", banner.order);
}


#pragma mark tableView网络请求
// tableView网络请求
- (void)tableViewHandleData
{
    NSString *str = @"http://api.liwushuo.com/v1/channels/1/items?limit=12&offset=0";
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSError *error = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *dic1 = [result objectForKey:@"data"];
        NSArray *arr = [dic1 objectForKey:@"items"];
        for (NSDictionary *dic in arr) {
            Choiceness *choiceness = [[Choiceness alloc] initWithDictionary:dic];
            [self.arr addObject:choiceness];
        }
        [self.myTableView reloadData];
    }];
}

#pragma  mark 设置MyTableView
- (void)installMyTableView
{
    //    CGRect rect = self.view.bounds;
    self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.backgroundColor = [UIColor clearColor];
    // 把scrollView放到tableView的头视图上
    self.myTableView.tableHeaderView = self.topView;
    [self.view addSubview:self.myTableView];
    // 注册cell
    [self.myTableView registerClass:[ChoicenessCell class] forCellReuseIdentifier:CHOICENESS];
//    [_myTableView release];
}

- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.myTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //进入刷新状态(一进入程序就下拉刷新)
    [self.myTableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.myTableView addFooterWithTarget:self action:@selector(footerRereshing)];
}


#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    
    //1. 在这调用请求网络数据方法（刷新数据）
    NSString *str = @"http://api.liwushuo.com/v1/channels/1/items?limit=12&offset=0";
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSError *error = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *dic1 = [result objectForKey:@"data"];
        NSArray *arr = [dic1 objectForKey:@"items"];
        [self.arr removeAllObjects];
        for (NSDictionary *dic in arr) {
            Choiceness *choiceness = [[Choiceness alloc] initWithDictionary:dic];
            [self.arr addObject:choiceness];
        }
        [self.myTableView reloadData];
    }];
    // 网络请求
    NSString *str1 = @"http://api.liwushuo.com/v1/banners";
    str1 = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [NetHandler getDataWithUrl:str1 completion:^(NSData *data) {
        // 解析数据
        NSError *error = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *dic = [NSDictionary dictionary];
        // 找出数组
        dic = [result objectForKey:@"data"];
        NSArray *arr = [dic objectForKey:@"banners"];
        [self.bannersArr removeAllObjects];
        for (NSDictionary *dic1 in arr) {
            // kvc赋值
            BannerGift *bannerGift = [[BannerGift alloc] initWithDictionary:dic1];
            // 把对象添加到数组
            [self.bannersArr addObject:bannerGift];
            
            //            [bannerGift release];
        }
        
    }];
    
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.myTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    //1. 拼接口等操作
    // 请求加载数据
    
    NSString *str = [NSString stringWithFormat:@"http://api.liwushuo.com/v1/channels/1/items?limit=12&offset=%ld", (long)self.num];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSError *error = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *dic1 = [result objectForKey:@"data"];
        NSArray *arr = [dic1 objectForKey:@"items"];
        for (NSDictionary *dic in arr) {
            Choiceness *choiceness = [[Choiceness alloc] initWithDictionary:dic];
            [self.arr addObject:choiceness];
        }
        //        [self.myTableView reloadData];
        self.num = self.num + 12;
    }];
    
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView reloadData];
        [self.myTableView footerEndRefreshing];
    });
}



-(NSString*) GetCurrntNet
{
    NSString* result;
    Reachability *r = [Reachability reachabilityWithHostname:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:     // 没有网络连接
            result=nil;
            break;
        case ReachableViaWWAN: // 使用3G网络
            result=@"3G";
            break;
        case ReachableViaWiFi: // 使用WiFi网络
            result=@"WiFi";
            break;
    }
    return result;
}

- (void)viewDidLoad {
//    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"精选";
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor ownColor];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];
//    // 扫一扫
//    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-saoyisao.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClicked:)] autorelease];
//    
//    self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 340, 280, 60)];
//    self.myLabel.numberOfLines = 0;
//    self.myLabel.font = [UIFont systemFontOfSize:14];
//    self.myLabel.backgroundColor = [UIColor whiteColor];
//    //    [self.view addSubview:self.myLabel];
//    [_myLabel release];
    
    
    [self tableViewHandleData];
    [self handleData];
    [NSTimer scheduledTimerWithTimeInterval:3.0f
                                     target:self
                                   selector:@selector(dismissAlert:)
                                   userInfo:nil
                                    repeats:NO];
    
        //    [self setupRefresh];
    
    // 抽屉按钮
    [self setupLeftMenuButton];
    
    // 缓冲
    self.hud = [[MBProgressHUD alloc]initWithView:self.view];
    [self.hud setMode:MBProgressHUDModeIndeterminate];
    
    self.hud.labelText = @"loading...";
    [self.hud show:YES];
    [self.view addSubview:_hud];
    [_hud release];
    
    // Do any additional setup after loading the view.
    
}

#pragma mark 抽屉按钮
// 设置navigation的左按钮为抽屉开关
- (void)setupLeftMenuButton
{
    MMDrawerBarButtonItem * leftDrawerButton = [[MMDrawerBarButtonItem alloc] initWithTarget:self action:@selector(leftDrawerButtonPress:)];
    [self.navigationItem setLeftBarButtonItem:leftDrawerButton animated:YES];
}
// 触发的方法
- (void)leftDrawerButtonPress:(id)sender{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}


#pragma mark 时间控制器
- (void)dismissAlert:(NSTimer *)timer{
    
    [UIView transitionWithView:self.topScrollView duration:0.5 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        
        CGFloat content = self.topScrollView.contentOffset.x + self.view.bounds.size.width;
        [self.topScrollView setContentOffset:  CGPointMake(content, 0)];
        
    } completion:^(BOOL finished) {
        
    }];
    
    if (self.topScrollView.contentOffset.x > self.view.bounds.size.width * self.bannersArr.count) {

        [self.topScrollView setContentOffset:CGPointMake(self.view.bounds.size.width, 0)];

    }
    //当偏移量小于第一张图片的偏移量偏移量变为最后一张图片的偏移量
    if (self.topScrollView.contentOffset.x < self.view.bounds.size.width) {

        [self.topScrollView setContentOffset:CGPointMake(self.view.bounds.size.width  * self.bannersArr.count, 0)];
   
    }
    //由于初始偏移量为屏幕宽度所以得到的页数 - 1
    self.topPageControl.currentPage = (self.topScrollView.contentOffset.x / self.topScrollView.bounds.size.width) - 1;
    [NSTimer scheduledTimerWithTimeInterval:3.0f
                                     target:self
                                   selector:@selector(dismissAlert:)
                                   userInfo:nil
                                    repeats:NO];

    
}

#pragma  mark 设置cell
// cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}
// 重用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 设置cell
    ChoicenessCell *cell = [tableView dequeueReusableCellWithIdentifier:CHOICENESS];
    Choiceness *chiceness = [self.arr objectAtIndex:indexPath.row];
    cell.choiceness = chiceness;
    [cell.likeButton addTarget:self action:@selector(likeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    cell.likeButton.tag = 3000 + indexPath.row;
    return cell;
}

// cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.bounds.size.height / 3.0;
}
// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 传值 push
    DetailsViewController *detailsVC = [[DetailsViewController alloc] init];
    detailsVC.choiceness = [self.arr objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:detailsVC animated:YES];
//    [detailsVC release];
    
    
}
#pragma mark 点赞按钮
- (void)likeButtonClicked:(UIButton *)button
{
    NSInteger numberofCell = button.tag - 3000;
    Choiceness *choiceness = [self.arr objectAtIndex:numberofCell];
    if (self.sum % 2 == 0) {
        self.sum = self.sum + 1;
        NSString *likeCount = choiceness.likes_count;
        NSInteger like_count = [likeCount integerValue];
        like_count = like_count + 1;
        choiceness.likes_count = [NSString stringWithFormat:@"%ld", like_count];
        [self.myTableView reloadData];
    } else {
        
        self.sum += 1;
        NSString *likeCount = choiceness.likes_count;
        NSInteger like_count = [likeCount integerValue];
        like_count = like_count - 1;
        choiceness.likes_count = [NSString stringWithFormat:@"%ld", like_count];
        [self.myTableView reloadData];
        
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


- (void)dealloc
{
    [_myTableView release];
    [_bigScrollView release];
    [_topScrollView release];
    [_arr release];
    [_myTableView release];
    [_bannersArr release];
    [_topView release];
    [_bannerGift release];
    [_myLabel release];
    [_myAlertView release];
    [_hud release];
    [super dealloc];
}


@end
